#include "server.h"
#include <mysql/mysql.h>



int getId(char *username, char *path, int *pid, MYSQL *mysql) {
    char sql[1024]={0};
    sprintf(sql,"select id from tree where username='%s' and path='%s';",username,path);
    int qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"filePid:%s\n",mysql_error(mysql));
        return -1;
    }

    MYSQL_RES *result=mysql_store_result(mysql);
    if(!result){
        fprintf(stderr,"mysql_store_result failed!\n");
        return -1;
    }

    MYSQL_ROW row=mysql_fetch_row(result);
    if(!row){
        fprintf(stderr,"No record found for username='%s' and path='%s'\n", username, path);
        mysql_free_result(result);
        return -1;
    }

    printf("atoi begin\n");
    printf("%s\n", row[0]);
    *pid=atoi(row[0]);
    printf("%d\n", *pid);

    mysql_free_result(result);
    return 0;
}

int  delToMk(MYSQL *mysql,const char* username,char* curr_path,char *filepath){
    char path[256]={0};
    memcpy(path,curr_path,strlen(curr_path));
    changePath(mysql,username,path,filepath);
    char sql[1024]={0};
    sprintf(sql,"select * from tree where path='%s' and username='%s' and tomb=1;",path,username);
    int qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"delToMk:%s\n",mysql_error(mysql));
    }
    MYSQL_RES *ret=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(ret);
    if(row!=NULL){
        
        memset(sql,0,sizeof(sql));
        sprintf(sql,"update tree set tomb=0 where where path='%s' and username='%s';",path,username);
        qret=mysql_query(mysql,sql);
        if(qret!=0){
            fprintf(stderr,"delToMk:%s\n",mysql_error(mysql));
        }
        return 1;
    }
    return 0;
}

int mkDir(MYSQL *mysql,char* username,char* curr_path,char *dirpath){
    char path[256]={0};
    strncpy(path,curr_path,sizeof(path)-1);
    path[sizeof(path)-1] = '\0';

    puts(path);
    puts(username);
    puts(dirpath);

    if(changePath(mysql,username,path,dirpath)!=-1){
        char sql[1024]={0};
        printf("front\n");
        sprintf(sql,"select * from tree where path = '%s' and username = '%s' and tomb = 1;",path, username);
        printf("rear\n");
        int qret=mysql_query(mysql,sql);
        if(qret!=0){
            fprintf(stderr,"mkDir:%s\n",mysql_error(mysql));
        }
        MYSQL_RES *result=mysql_store_result(mysql);
        MYSQL_ROW row=mysql_fetch_row(result);
        if (!row) {
            printf("文件夹已存在\n");
            return 0;
        } else {
            memset(sql, 0, sizeof(sql));
            time_t createtime = time(NULL);
            char *t = ctime(&createtime); 
            if (t && t[strlen(t)-1] == '\n') {t[strlen(t)-1] = '\0';}
            snprintf(sql,sizeof(sql),"update tree set tomb = 0, createtime = '%s' where path = '%s' and username = '%s';", t, path, username);
            int qret=mysql_query(mysql,sql);
            if(qret!=0){
                fprintf(stderr,"mkDir:%s\n",mysql_error(mysql));
            }
            return 1;
            
        }

    }else{
        puts("555");
        memset(path,0,sizeof(path));
        strncpy(path,curr_path,sizeof(path)-1);
        path[sizeof(path)-1] = '\0';
        char left[128]={0},right[128]={0};
        cutTail(dirpath,left,right);
                if(strlen(left) == 0 || strlen(right) == 0){
            fprintf(stderr,"path is invalid!\n");
            return 0;
        }
        printf("%s\n%s\n", left, right);

        if(changePath(mysql,username,path, left)==-1){
            printf("父路径不存在\n");
            return 0;
        }else{
            int id = 0;
            int getId_ret =getId(username,path,&id,mysql);

            if(getId_ret != 0){
                fprintf(stderr,"Failed to get parent directory ID\n");
                return 0;
            }
            // 安全拼接路径
            size_t current_len = strlen(path);
            size_t add_len = strlen("/");
            size_t right_len = strlen(right);
            
            if (current_len + add_len + right_len >= sizeof(path)) {
                fprintf(stderr, "路径拼接超出长度限制\n");
                return 0;
            }
            
            if (strcmp(path, "/") != 0) {
                strcat(path, "/");
            }
            strcat(path, right);
            
            // 使用参数化查询防止SQL注入
            char sql[1024] = {0};
            time_t createtime;
            time(&createtime);
            char *t = ctime(&createtime);
            snprintf(sql, sizeof(sql),
                "INSERT INTO tree (name, username, path, pre_id, md5, tomb, size, createtime) "
                "VALUES('%s', '%s', '%s', %d, '0', 0, 0, '%s');",
                right, username, path, id,t);
            
            // 转义特殊字符（可选）
            // 对于简单场景可直接使用snprintf，复杂场景建议使用mysql_real_escape_string
            
            int qret = mysql_query(mysql, sql);
            if (qret != 0) {
                fprintf(stderr, "mkDir: %s\n", mysql_error(mysql)); 
            }
        }
    }
    return 1;
}

int insertRoot(MYSQL *mysql, char *username) {
    time_t createtime;
    time(&createtime);
    char *t = ctime(&createtime); 
    if (t[strlen(t)-1] == '\n') t[strlen(t)-1] = '\0';

    // 转义 username
    char escaped_username[256];
    mysql_real_escape_string(mysql, escaped_username, username, strlen(username));

    char sql[1024] = {0};
    sprintf(sql, "insert into tree (name, username, path, pre_id, md5, size, createtime, tomb) values ('/', '%s', '/', -1, '0', 0, '%s', 0);", escaped_username, t);

    int qret = mysql_query(mysql, sql);
    if (qret != 0) {
        // 打印更详细的错误信息
        fprintf(stderr, "insertRoot: SQL query failed: %s\n", mysql_error(mysql));
        fprintf(stderr, "SQL query: %s\n", sql);
        return -1;
    }
    return 0;
}
int rmDir(MYSQL *mysql,char* username,char* curr_path,char *dirpath) {
    char path[256]={0};
    memcpy(path,curr_path,strlen(curr_path));
    if(changePath(mysql,username,path,dirpath)==-1){
        return 0;
    }else{
        char sql[1024]={0};
        sprintf(sql,"select id from tree  where path='%s' and md5='0' and username = '%s';",path, username);
        int qret=mysql_query(mysql,sql);
        if(qret!=0){
            fprintf(stderr,"rmdir select:%s\n",mysql_error(mysql));
        } 
        MYSQL_RES *result=mysql_store_result(mysql);
        MYSQL_ROW row=mysql_fetch_row(result);
        if(row==NULL){
            return 0;
        }else{
            memset(sql,0,sizeof(sql));
            sprintf(sql,"select * from tree where pre_id=%d and username = '%s' and tomb = 0;",atoi(row[0]), username);
            qret=mysql_query(mysql,sql);
            if(qret!=0){
                fprintf(stderr,"rmdir select:%s\n",mysql_error(mysql));
            }
            MYSQL_RES *ret=mysql_store_result(mysql);
            MYSQL_ROW r=mysql_fetch_row(ret);
            if(r==NULL){
                memset(sql,0,sizeof(sql));
                sprintf(sql,"update tree set tomb=1 where path='%s' and username = '%s';",path, username);
                qret=mysql_query(mysql,sql);
                if(qret!=0){
                    fprintf(stderr,"rmdir update:%s\n",mysql_error(mysql));
                }
                return 1;
            }else{
                return 0;
            }
        
        }
    }
    return 0;
}


int removeFile(MYSQL *mysql,const char* username,char* curr_path,char *filepath){
    char path[256]={0};
    memcpy(path,curr_path,strlen(curr_path));
    if(changePath(mysql,username,path,filepath)==-1){
        return 0;
    }else{
        char sql[1024]={0};
        sprintf(sql,"update tree set tomb=1 where path='%s' and username = '%s';",path, username);
        int qret=mysql_query(mysql,sql);
        if(qret!=0){
            fprintf(stderr,"remove:%s\n",mysql_error(mysql));
        }
        return 1;
    }
}



void insertFile(char *filename,char *filepath,int filesize,char *filemd5,char *user, int parent, MYSQL *mysql){
    char sql[1024]={0};
    time_t createtime;
    time(&createtime);
    char *t = ctime(&createtime); 
    if (t[strlen(t)-1] == '\n') t[strlen(t)-1] = '\0';
    sprintf(sql,"insert into tree (name,username,path, pre_id,md5,size,createtime,tomb) values('%s','%s','%s',%d ,'%s', %d,'%s', %d);",filename,user,filepath,parent,filemd5,filesize,t, 0);
    int qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"insertFile:%s\n",mysql_error(mysql));
    }
}

int searchMd5(char *md5,MYSQL *mysql, char *size){
    char sql[1024]={0};
    sprintf(sql,"select md5 size from tree where md5='%s' and tomb = 0;",md5);
    int qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"searchMd5:%s\n",mysql_error(mysql));
    }
    MYSQL_RES *result=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(result);
    if(row==NULL){
        return 0;
    }else{
        memcpy(size, row[1], strlen(row[1]));
        return 1;
    }
}

int searchFile(char *path, MYSQL *mysql, char *user, char *md5path, char *home) {
    char sql[1024]={0};
    sprintf(sql,"select md5 from tree where path='%s' and username = '%s' and tomb = 0;",path, user);
    int qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"searchMd5:%s\n",mysql_error(mysql));
        
    }
    MYSQL_RES *result=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(result);
    strcat(md5path, home);
    strcat(md5path, "/");
    strcat(md5path, row[0]);
    return 0;
}

